
package csc.daonjpa.java.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import csc.daonjpa.java.dao.AccountDAO;
import csc.daonjpa.java.dao.CardDAO;
import csc.daonjpa.java.dao.CustomerDAO;
import csc.daonjpa.java.domain.Account;
import csc.daonjpa.java.domain.BaseInfor;
import csc.daonjpa.java.domain.Card;
import csc.daonjpa.java.domain.Customer;

/**
 * This controller handles account related actions
 * @author nvu3
 *
 */
@Controller
@RequestMapping(value = "/card")
public class CardController {
	@Autowired
	private CardDAO cardDAO;
	
	@Autowired
	private CustomerDAO customerDAO;
	
	@RequestMapping
	public String goCard(Model model){
		Authentication auth = SecurityContextHolder.getContext().getAuthentication();
		String loginId = auth.getName();
		
		List<Card> cards = cardDAO.getCards(loginId);
		model.addAttribute("cards", cards);
		return "card";
	}
	
	/**
	 * Adds account to DB
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/createCard")
	public String addAccount(HttpServletRequest request, Model model) {
		// Read account info from request and save into Account object
		String cardType = request.getParameter("cardType");
		String cardNumber = request.getParameter("cardNumber");
		String availableAmount = request.getParameter("availableAmount");
		
		Authentication auth = SecurityContextHolder.getContext().getAuthentication();
		String loginId = auth.getName();
		Customer customer = customerDAO.getCustomer(loginId);
		
		Card card = new Card();
		card.setCardType(cardType);
		card.setNumber(cardNumber);
		card.setAmount(availableAmount);
		card.setCustomer(customer);
		
		// Save account to DB
		cardDAO.addCard(card);
		
		List<Card> cards = cardDAO.getCards(loginId);
		model.addAttribute("cards", cards);
		
		return "card";
	}
}
